package com.mytijian.runtime.executor;

import java.lang.reflect.Method;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mytijian.exception.BizSystemException;
import com.mytijian.runtime.RuntimeExceptionEnum;
import com.mytijian.runtime.model.service.AliService;
import com.mytijian.runtime.model.service.ServiceFacade;
/**
 * 服务工作者工厂，提供服务工作者创建功能
 * @author Administrator
 *
 */
@Component
public class ServiceWorkerFactory {

	@Autowired
	private List<ServiceFacade> serviceFacades;

	public ServiceWorker createService(String serviceName) {
		// 从缓存中获取服务工作者
		ServiceWorker serviceWorker = ServiceWorkerCache.getServiceWorker(serviceName);
		if (serviceWorker != null) {
			return serviceWorker;
		}
		// 创建服务工作者,双重检查解决并发重复创建问题
		serviceWorker = ServiceWorkerCache.getServiceWorker(serviceName);
		if (serviceWorker == null) {
			synchronized (ServiceWorkerFactory.class) {
				serviceWorker = createServiceWorker(serviceName);
				ServiceWorkerCache.putServiceWorker(serviceName, serviceWorker);
			}
		}
		return serviceWorker;
	}

	private ServiceWorker createServiceWorker(String serviceName) {
		for (ServiceFacade serviceFacade : serviceFacades) {
			Method[] methods = serviceFacade.getClass().getMethods();
			for (Method method : methods) {
				AliService aliService = method.getAnnotation(AliService.class);
				if (aliService != null && aliService.aliMethodName().equals(serviceName)) {
					return new ServiceWorker(method, serviceFacade);
				}
			}
		}
		throw new BizSystemException(RuntimeExceptionEnum.SERVICE_NOT_EXIST, null);
	}

}
